<?php
// +----------------------------------------------------------------------
// | RXThinkCMF框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2020 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: 牧羊人 <1175401194@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\service\OfTrademarkService;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\View;

/**
 * 商标管理-控制器
 * @author 牧羊人
 * @since: 2021/12/24
 * Class Oftrademark
 * @package app\admin\controller
 */
class Oftrademark extends Backend
{
    /**
     * 初始化方法
     * @author 牧羊人
     * @since: 2021/12/24
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model            = new \app\admin\model\OfTrademark();
        $this->service          = new OftrademarkService();
        $this->OfcompanyService = new \app\admin\service\OfCompanyService();
        $this->Ofcontract       = new \app\admin\model\OfContract();
        $this->OfCompanyModel   = new \app\admin\model\OfCompany();
    }

    /**
     * 数据列表页
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function index()
    {
        $company_id = input("company_id", 0);
        View::assign("company_id", $company_id);

        $statusList      = config('admin.patentnotice_rademark_status');
        $trademark_speed = config('admin.trademark_speed');
        if (IS_POST) {
            $result = $this->service->getList();
            foreach ($result['data'] as $key => &$value) {
                $result['data'][$key]['status']     = $statusList[$value['status']];
                $result['data'][$key]['expire_day'] = date("Y-m-d", strtotime("-1 years", strtotime($result['data'][$key]['end_date'])));
                $result['data'][$key]['speed']      = $trademark_speed[$value['speed']];
            }
            return $result;
        }

        View::assign("statusList", $statusList);

        View::assign("trademark_speed", $trademark_speed);
        return parent::index(); // TODO: Change the autogenerated stub
    }

    /**
     * 添加或编辑
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 牧羊人
     * @since 2020/7/2
     */
    public function edit()
    {
        if (IS_POST) {
            //检查唯一编号是否存在 排除自身
            $param        = request()->param();
            $apply_number = $param['apply_number'];

            $map = [
                ['apply_number', '=', $apply_number],
                ['mark', '=', 1],
            ];
            if ($param['id']) {
                $map[] = ['id', '<>', $param['id']];
            }
            $isset = $this->model->where($map)->value("id");
            if ($isset) {
                return message("商标申请号已存在", false);
            };
            $company_id = input('company_id','');
            if(!$company_id){
                return message('请选择正确的客户',false);
            }
            $result = $this->service->edit();
            return $result;
        }
        // 客户列表
        $companyMod = new \app\admin\model\OfCompany();
        $list       = $companyMod->where("mark", 1)->order("id desc")->select()->toArray();
        View::assign("list", $list);

        $info         = [];
        $id           = input("get.id", 0);
        $contractInfo = "";
        if ($id) {
            $info = $this->model->getInfo($id);
            if (!empty($info['contract_id'])) {
                $contractInfo = Db::name("of_contract")->where("id", $info['contract_id'])->find();
            }
        } else {
            $data = func_get_args();
            if (isset($data[0])) {
                foreach ($data[0] as $key => $val) {
                    $info[$key] = $val;
                }
            }
        }
        $statusList = config('admin.patentnotice_rademark_status');
        View::assign("statusList", $statusList);

        View::assign("contractInfo", $contractInfo);
        View::assign("info", $info);

        $trademark_speed = config('admin.trademark_speed');
        View::assign("trademark_speed", $trademark_speed);
        return $this->render();
    }

    /**
     * 弹窗添加 通知书
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function add_notice()
    {
        $param = request()->param();

        View::assign("id", $param['id']);
        return $this->render();
    }

    /**
     * 批量添加数据列表页
     * https://blog.csdn.net/lmy1998/article/details/118420437 参考此处 原先导入的模式 因为7.4的原因语法报错
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function batch_import()
    {
        if (IS_POST) {
            $param = request()->param();
            $data  = $this->getUrl($param['url']);
            if (!$data) {
                return message();
            }
            return message($data, false);
        } else {
            return $this->render();
        }

    }

    /**
     * 客户必填 合同编号必填
     * 查重
     * 不能为空
     * 如果错误则不让导入
     */
    public function getUrl($path)
    {
        ini_set('max_execution_time', '0');
        $msg = '';

        $file = 'uploads/' . $path;
        if (!is_file($file)) {
            return "\n 请选择文件";
        }
        $data = $this->OfcompanyService->readFile($file, 1);
        if (!$data) {
            $msg .= "\n 没有可导入的数据,请确认导入的文件正确";
            return $msg;
        }

        $save_data = [];
        foreach ($data as $k => $item) {
            //判断模板是否正确
            if ($k == 1) {
                if ($item[0] !== '客户名称' || $item[9] !== '商标名称' || $item[6] !== '申请号' || $item[15] !== '申请人') {
                    $msg .= "\n 模板错误请选择正确的模板进行导入";
                    return $msg;
                }
                continue;
            }
            //跳过空行
            $is_empty = '';
            foreach ($item as $key => $value) {
                $is_empty .= $value;
            }
            if (!$is_empty) {
                continue;
            }

            //对必填的列判断
            if (empty($item[0])) {
                $msg .= "\n" . $k . "行:客户名称未填写";
                return $msg;
            }
            if (empty($item[9])) {
                $msg .= "\n" . $k . "行:商标名称未填写";
                return $msg;
            }

            //客户名称必填 且需要查询出id
            $company_id = $this->OfCompanyModel->where('name', $item[0])->where('mark', 1)->value('id');
            if (!$company_id) {
                $msg .= "\n" . $k . "行:客户未匹配";
                return $msg;
            }

            $contract_id = 0;
            if ($item[1]) {
                $contract_id = $this->Ofcontract->where('contract_no', $item[1])->where('mark', 1)->value('id');
                if (!$contract_id) {
                    $msg .= "\n" . $k . "行:合同编号未匹配到合同";
                    return $msg;
                }
            }

            $speed = 0;
            if ($item[2]) {
                $speedList = config('admin.trademark_speed');
                if (!in_array($item[2], $speedList)) {
                    $msg .= "\n" . $k . "行:案件进度错误";
                    return $msg;
                }
                foreach ($speedList as $key => $value) {
                    if ($item[2] == $value) {
                        $speed = $key;
                    }
                }
            }

            $status = 0;
            if ($item[3]) {
                $statusList = config('admin.patentnotice_rademark_status');
                if (!in_array($item[3], $statusList)) {
                    $msg .= "\n" . $k . "行:案件状态错误";
                    return $msg;
                }
                foreach ($statusList as $key => $value) {
                    if ($item[3] == $value) {
                        $status = $key;
                    }
                }
            }

            //申请号唯一
            if ($item[6]) {
                $is_in_data = $this->OfcompanyService->checkDuplicate([['apply_number' => $item[6]]], $save_data);
                if ($is_in_data) {
                    $msg .= "\n" . $k . "行:申请号重复(当前导入的表格中存在相同的申请号)";
                    return $msg;
                }

                $is_set = $this->model->where('apply_number', $item[6])->where('mark', 1)->value('id');
                if ($is_set) {
                    $msg .= "\n" . $k . "行:申请号重复(数据库中已存在)";
                    return $msg;
                }

            }

            $item10 = $this->OfcompanyService->changDate($item[10]);
            $item12 = $this->OfcompanyService->changDate($item[12]);
            $item13 = $this->OfcompanyService->changDate($item[13]);

            //优先查重表格
            $excel_map = [
                ['company_id' => $company_id],
                ['brand_name' => $item[9]],
            ];
            $is_excel_set = $this->OfcompanyService->checkDuplicate($excel_map, $save_data);
            if ($is_excel_set) {
                $msg .= "\n" . $k . "行:重复(当前导入的表格中存在相同客户与商标名称)";
                return $msg;
            }

            //查重 专利名称+客户
            $map = [
                ['mark', '=', 1],
                ['company_id', '=', $company_id],
                ['brand_name', '=', $item[9]],
            ];
            $is_set = $this->model->where($map)->value('id');
            if ($is_set) {
                $msg .= "\n" . $k . "行:重复(数据库中存在相同客户与商标名称)";
                return $msg;
            }

            $save_data[] = [
                'company_id'     => $company_id,
                'contract_id'    => $contract_id,
                'speed'          => $speed,
                'status'         => $status,
                'project_number' => $item[4],
                'score'          => $item[5],
                'apply_number'   => $item[6],
                'business_name'  => $item[7],
                'services'       => $item[8],
                'brand_name'     => $item[9],
                'apply_date'     => $item10,
                'notice'         => $item[11],
                'start_date'     => $item12,
                'end_date'       => $item13,
                'remark'         => $item[14],
                'create_time'    => time(),
                'update_time'    => time(),
                'applicant'      => $item[15],
            ];
        }
        if (!$save_data) {
            $msg .= "\n 没有可导入的数据,请确认导入的文件正确";
            return $msg;
        }

        $res = $this->model->saveAll($save_data);
        if ($res) {
            $msg .= "";
        } else {
            $msg .= "\n 插入未知错误";
        }
        return $msg;
    }

    public function download()
    {
        ini_set('max_execution_time', '0');
        $param = request()->param();
        // 查询要导出的数据
        $map = [
            ['mark', '=', 1],
        ];
        if ($param['project_number']) {
            $map[] = ['project_number', 'like', '%' . $param['contract_no'] . '%'];
        }
        if ($param['speed'] != '') {
            $map[] = ['speed', '=', $param['speed']];
        }
        if ($param['status'] != '') {
            $map[] = ['status', '=', $param['status']];
        }
        // 客户名称
        if ($param['company_id']) {
            $map[] = ['company_id', '=', $param['company_id']];
        }else{            
            $admin_id = session("adminId");
            if($admin_id != 1){                 
                $wh_or = [];
                $wh_or[] = ["service_id","=",$admin_id];
                $wh_or[] = ["agent_id","=",$admin_id];
                $wh_or[] = ["peer_id","=",$admin_id];
                $arr_ids = Db::name("of_company")->where('mark',1)->where(function($query) use($wh_or){$query->whereOr($wh_or);})->column("id");
                if(!empty($arr_ids)){
                    $map[] = ['company_id', 'in', $arr_ids];            
                }
            }
        }

        $head = [
            ['title' => '客户名称', 'width' => 50],
            ['title' => '合同编号', 'width' => 15],
            ['title' => '案件进度', 'width' => 15],
            ['title' => '案件状态', 'width' => 15],
            ['title' => '案件编号', 'width' => 15],
            ['title' => '国际分类', 'width' => 15],
            ['title' => '申请号', 'width' => 20],
            ['title' => '业务名称', 'width' => 50],
            ['title' => '商品服务', 'width' => 50],
            ['title' => '商标名称', 'width' => 50],
            ['title' => '申请日', 'width' => 15],
            ['title' => '初审公告通知书', 'width' => 20],
            ['title' => '专用权开始', 'width' => 15],
            ['title' => '专用权结束', 'width' => 15],
            ['title' => '备注', 'width' => 30],
            ['title' => '申请人', 'width' => 15],
        ];

        $data = $this->model->where($map)->order('id desc')->select();

        $new_data = [];
        foreach ($data as $key => $v) {
            $tmp = [];
            //客户名称 名称获取
            $name = Db::name("of_company")->where("id", $v['company_id'])->value('name');
            //合同编号
            $contract_no = Db::name("of_contract")->where("id", $v['contract_id'])->value('contract_no');
            //案件进度
            $speedlist = config('admin.trademark_speed');
            $speed     = $speedlist[$v['speed']];
            //案件状态
            $statusList = config('admin.patentnotice_rademark_status');
            $status     = $statusList[$v['status']];

            $tmp[] = $name;
            $tmp[] = $contract_no;
            $tmp[] = $speed;
            $tmp[] = $status;
            $tmp[] = $v['project_number'];
            $tmp[] = $v['score'];
            $tmp[] = $v['apply_number'];
            $tmp[] = $v['business_name'];
            $tmp[] = $v['services'];
            $tmp[] = $v['brand_name'];
            $tmp[] = $v['apply_date'];
            $tmp[] = $v['notice'];
            $tmp[] = $v['start_date'];
            $tmp[] = $v['end_date'];
            $tmp[] = $v['remark'];
            $tmp[] = $v['applicant'];

            $new_data[] = $tmp;
        }
        $fileName = '商标(' . date("Y-m-d H:i:s") . ')';
        $this->OfcompanyService->exportExcel($head, $new_data, $fileName);
    }

}
